<?php
/**
 * Created by PhpStorm.
 * User: HM22
 * Date: 2019/4/27
 * Time: 16:34
 */

namespace app\admin\controller;

use my\Security;
use think\Db;
use AliPay\AlipayFundTransToaccountTransferRequest;
use Alipay\AlipayService;
use my\Tools;

class DriverWithdraw extends Base
{
    ///*正式环境支付宝 密钥*/
    private $appid = '2019040963872154';  //电脑网站支付的应用的APPID
    private $signType = 'RSA2'; //签名算法类型，支持RSA2和RSA，推荐使用RSA2

    private $saPrivateKey = 'MIIEpAIBAAKCAQEArUfFDtz7sE2nwnYTn4i8YTIseXM5lmoqQCMwo5FyMmlbDrFPsaFGhZH/f//o33PUZ4FoFBugYL+Tiop2mkK3t0XVxfSo3SjHjdk7uNcyBTHJLd9oEiRNV4V74iZhCkjSj9BmpZzVNrU4djZ6pRlK2arqAPwt9p7Tyd22iBS9i5WRRdJTnyz2YPh6POPXspae1YIsZn7uAOxt9o9kzD2P9wbkZJT3xLBG3zmZR5kO3Lh4aEymCC9QlOG6QeUMQWym1A3Op0elobGN4oj/ZKAgNLOnt6yWK9DzzFYXx4ZwCVEqCO/SeqCVsbnQy/AeQnTlSbhI6vADTAwwVZ8udtsjkQIDAQABAoIBAGx9KtuLb+mKNSaDVvXjXk5cY4wGoF+USK+vWJyQS7dUTzZ7vTGxj73BEv7I8rw0gR/s3YT5Zwgr6ewrlOYwL2YHyzgNXkxZY9dj0wh/c0ndSd/2p+nz4JiTcmS9MrSFs49nI109PCDshVU99ru3gi2V3LyRJxXpiyAwOEAq/CGPkvMxaysX5wo35GQVfGHvRb2Zi9Um3JxHKHgHhRjbXHmu7HfeV0mi3MzIr/aPXE/SjgzZFRKqj7OKkOfi4nud1cEEiclpTOGQ12JiDCTHNsf/y3+P3OVxVljXB7Ic91grCnsioXkdYakpjHcUXZdeC0dP1YMyrXJxCZ6QGqYRY4ECgYEA4YJ/CPFotKWATOZz36CyYA8GyXPsmMKDX74E1kx4EfzUJPOFXzztWAvr4cIuV+kz/4Uwpk7U1hh7JDKe3OECA05gzRwjOenafLOX9yDViFZjWCAsTouV/gfeTD2hKrR3awGW5MX9OLhgp+biE2Be5pBC6UOqG7vzH/PEMBalJM0CgYEAxLV474+M8M+wyUnlzxh1Cu+dN9TbZL813alLCUfqsYFW5VUkduO8gQVIDBPFVmBIinXBy6Rkfv1o54BNQgDVJJo5sPKw4nEHYFL4IQdToU6GfmncPYKxel7psQcyOfgmC6fIjbNyiBt33t712xgEtXhA74gTo4zpuMnpaSZJmdUCgYEAne7QnSjE1c8avcCf4jwe8JtVe3zOdGW1sDXaGWNQq/hPctmBzKNU7dbbii5+Wl8eZZOX8MFA2fgnNcCl9bc3u60Gql9MZGDc/Xyhrxe1tFgcFznhDdlAYLqN+wMmfkwJXk2sqefnYfPu7WgLaNqTXBIoaklTNz04FmaYPb1+RvkCgYB3CgsBjjGQmV82sM2tofNShubxnpKWSVBjr8uE9kyE1uyrI/dJK1AsE/IhvOUy/Flp0RFSF03pu5j8X5xhUPeritlWx8dbgWMhW5RlCHYHq+mgHpf1cV3N3Bo3008F3bHIY+TuO6YXz+eeq/bEe6h92SQS0Jpx4xidhzMFOvJXcQKBgQCpMyLR9KoKZatdrulcXD3oQ3Ya1dWiSfkDmQPJ5VUV2a6i53cDWNpF4KJRD8ot1jvaTCYEldiZW+CzuY0o7vlw7W2vwAPXmQuHWrV0aUEtnMmb9p+g8CiSqDoSb2ghBkLob4kjwWG8l7YwpnsR0S38OfetH0i271gIX0Nz6Jx2QA==';


//    /*测试  沙箱环境支付宝 密钥*/
//    private $appid = '2016092700609124';  //电脑网站支付的应用的APPID
//
//    private $signType = 'RSA2'; //签名算法类型，支持RSA2和RSA，推荐使用RSA2
//
//    private $saPrivateKey = 'MIIEpAIBAAKCAQEA0yS2cV1zZpkJtrVuyXWKfSESiUOPucVh9ofdqv5kVRRF2/X1QhdLj/zAyMo257LuagDDnToL6xKMgO/ihXJjbY0U83US0OykNLgZ0BcW65gODqchAENVcT+dhd/4z1z7VMKymAd+KVvqmV7siwh1ffULg03V0d/OHnqN2PFrF2cTe22eLojcHQJF0/N6vxDDejzmTetjXWrpGo0JFwJz14eKfOjZ+pyIqJcpwtgWROK5wRFu9PhbMvB9PtouuKsyVkA+Ijn5Nd5i0cqPLX752uV72VjPUD2MqPBl4twhOGi2CcmbOsJt7aOZoRyzZhtPGLZfnraR5GUcV5c4O2QflQIDAQABAoIBAAUBr9nMT3o1UsekUbYxNVF2QUxD79qF1abU3eq6EYL68hUfJeulRcNqSN/5+4dO9NxKnFjUEYhHblF4XrSvW7AzUjXbptCRa+tcGjCW+5Imjt7GE8A/2HzQ91k/UFUKbWM7IqT8OH+ekFeGqrE5SB/ueZFpfRJ27hpG6aolP1bUrc+bpegFVEePB8r/MOeOlVM66nnwTpCG3UJziEDEbXkJ2RpMTMPqor4W4Yqn1xqvQaA4JaDOTuocF5kowG9S+DsYi2SzOSlCSRiPAVNVUZWzYwcJPbaLtthUx5u9KU2ADWDkNqbhzrrBY8nFMKX7yHSP/gZdt9J+cQQo0RemOgECgYEA/DoQW9GVvUJcUp0v7FKXbFOxEPv2Bo03QkiRYc9kpmH5HTLKaIoVSoeHO67xXlKG6GrbK1+6JX1NFGBLz+585gqAOpHsTfbluE+L/2bbdCt5m6OSbnONUAjSHNX8N0eA2ImKfEcX9Fe1CUmmoGkiGix/Xo/hudRUgHc9Jz79uEECgYEA1k1QfWSnSttrvYFkWucfP8nsvxrOuzwIhqULWiJGH5X03pqbzAJA9N3pcUi3+RiEnwONRRLITgWIxT60U5NBz2pDZI2Q53XBQZj2GMfZu+FXVB1Zh3IIosEgmgPaJCYOmSUMyXAhens5mA7Q8IecOSYg1S3YG5HVYnL+mKbZclUCgYBPMGuyaDr7ELqrtW42ZDfmauBM1M6JgAy5Ys9CRjrzgg8Ue73Q1ImavLJYqrRdSMvSbLojBAsNeimZHCKxRc8w6lsYCHiIgdvd4huyNDjyYDPuCY0P4HediSdupkBpmql5UrWID0oWDPNp1xXZhyiNzyquJb5Y+bEOJGGu0LgYAQKBgQDKfbFxWnsso1oRbULLFhoT5xOZm5X9mwMfXrH0T/BchhAjiolt4i9IcKrUzPZxG3as3elNfCridh4+6jnvwnPrrafSSmXCHyUle4gF8EjPW2Rt6XGgJuL8DmpkvQERKRigIj8L07T+i5LnGBDbRfgak+lwJWpO2qR66tegm/9ZJQKBgQDFD8iYmMWaxGqZlrWnwMuEjoyOmw1eXOWCxZsFvtXjlRFQkKz752Wo0QiRngTdgV6J1R8cpG4BGIhourGTL32JUqn6ByTLBeJhnTHRBfGGHmtv56n00Q7DWxjKKUEUdOw/KxEmO5jBNzQdy2Ksp+xzKs6UJ3J89rQbjpP0NzOiNQ==';

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    //提现页面
    public function index()
    {
        $config['admin'] = session('admin_name');
        $config['url'] = url('table');
        $config['pay_type'] = input('get.pay_type') ?: 1; //提现方式 1 支付宝 2 微信 3 银行卡
        $config['pay_status'] = [
            '1' => '待支付',
            '2' => '已支付',
            '3' => '支付失败',
        ];
        $config['driver_type'] = [
            '1' => '快车',
            '2' => '城际',
        ];
        $this->assign($config);
        return $this->fetch();
    }

    public function table()
    {
        $map['a.type'] = 2;//提现 2
        //type=2时，0审核中，1通过，2已打款，9驳回
        $map['a.audit_status'] = input('get.audit_status') ?: 1;

        $page = input('get.page') ?: 1;
        $limit = input('get.limit') ?: 10;

        $field = "a.*,f.real_name,f.bank_num,b.driver_phone,b.driver_name";
        $res = Db::table('xm_driver_wallet a')
            ->join(['xm_driver_bank' => 'f'], 'f.driver_id = a.driver_id', 'LEFT')
            ->join(['xm_driver' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
            ->field($field)
            ->where($map)->page($page, $limit)
            ->order('a.id desc')->select();

        foreach ($res as $key => $value) {
            $res[$key]['wind_add_time'] = date('Y-m-d H:i:s', $value['wind_add_time']);
            $res[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            $res[$key]['money'] = sprintf("%.2f", abs($value['money']) / 100);
            $res[$key]['admin_time'] = $value['admin_time']==''?'':date('Y-m-d H:i:s', $value['admin_time']);
            $res[$key]['admin_pay_time'] = $value['admin_pay_time']==''?'':date('Y-m-d H:i:s', $value['admin_pay_time']);

        }

        $count = Db::table('xm_driver_wallet a')
            ->join(['xm_driver_bank' => 'f'], 'f.driver_id = a.driver_id', 'LEFT')
            ->join(['xm_driver' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
            ->where($map)->count();

        echo json_encode([
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ]);
    }

    //提现 搜索
    public function searchIndex()
    {
        $page = input('get.page') ?: 1;
        $limit = input('get.limit') ?: 10;

        $map['f.type'] = 2; //提现
        $map['f.pay_type'] = 1;//提现方式 1 支付宝 2 微信 3 银行卡

        $driver_name = trim(input('get.driver_name'));
        $driver_phone = trim(input('get.driver_phone'));
        $account_number = trim(input('get.account_number'));
        $driver_type = input('get.driver_type');
        $pay_status = input('get.pay_status');
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));

        input('get.start') && $map['a.add_time'] = array('egt', $start);
        input('get.end') && $map['a.add_time'] = array('elt', $end);
        input('get.start') && input('get.end') && $map['a.add_time'] = array('between', array($start, $end));
        $driver_name && $map['driver_name'] = $driver_name;
        $driver_phone && $map['driver_phone'] = Security::encrypt($driver_phone);
        $account_number && $map['f.alipay_account'] = $account_number;
        $driver_type && $map['b.driver_type'] = $driver_type;
        $pay_status && $map['a.pay_status'] = $pay_status;

        $field = "a.*,f.pay_type,f.money,f.admin_name,f.alipay_username,f.alipay_account,f.add_time as wind_add_time,f.balance_withdraw,f.award_withdraw,b.driver_id,b.driver_type,driver_phone,driver_name";
        $res = Db::table('xm_driver_withdraw_record a')
            ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = a.flow_id', 'LEFT')
            ->join(['xm_driver_base' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
            ->field($field)
            ->where($map)->page($page, $limit)
            ->order('a.is_pay asc, a.id desc')->select();

        foreach ($res as $key => $value) {
            $res[$key]['driver_phone'] = Security::decrypt($value['driver_phone']);
            $res[$key]['wind_add_time'] = date('Y-m-d H:i:s', $value['wind_add_time']);
            $res[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            $res[$key]['money'] = sprintf("%.2f", abs($value['money']) / 100);
            $res[$key]['balance_withdraw'] = sprintf("%.2f", abs($value['balance_withdraw']) / 100);
            $res[$key]['award_withdraw'] = sprintf("%.2f", abs($value['award_withdraw']) / 100);
            if ($value['admin_time'] != '' && $value['pay_status'] == 1) {
                //字段 处理时间 为  审核时间
                $res[$key]['admin_time'] = date('Y-m-d H:i:s', $value['admin_time']);
            } elseif ($value['admin_time'] == '' && $value['pay_status'] == 1) {
                //未支付的 待支付状态 处理时间为空
                $res[$key]['admin_time'] = '';
            } else {
                //字段 处理时间 为  支付时间
                $res[$key]['admin_time'] = date('Y-m-d H:i:s', $value['pay_time']);
            }
        }

        $count = Db::table('xm_driver_withdraw_record a')
            ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = a.flow_id', 'LEFT')
            ->join(['xm_driver_base' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
            ->where($map)->count();

        echo json_encode([
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ]);
    }

    /**
     * 导出excel
     * @param string
     * @param int
     * @return string 成功时返回
     */
    public function excel()
    {
        $type = input('get.type');
        $page = input('get.page') ?: 1;
        $limit = $type == 1 ? 1000 : input('get.limit');
        $header = json_decode(input('get.headers'));

        $map['f.type'] = 2; //提现
        $map['f.pay_type'] = 1;//提现方式 1 支付宝 2 微信 3 银行卡

        $driver_name = trim(input('get.driver_name'));
        $driver_phone = trim(input('get.driver_phone'));
        $account_number = trim(input('get.account_number'));
        $driver_type = input('get.driver_type');
        $pay_status = input('get.pay_status');
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));

        input('get.start') && $map['a.add_time'] = array('egt', $start);
        input('get.end') && $map['a.add_time'] = array('elt', $end);
        input('get.start') && input('get.end') && $map['a.add_time'] = array('between', array($start, $end));
        $driver_name && $map['driver_name'] = $driver_name;
        $driver_phone && $map['driver_phone'] = Security::encrypt($driver_phone);
        $account_number && $map['f.alipay_account'] = $account_number;
        $driver_type && $map['b.driver_type'] = $driver_type;
        $pay_status && $map['a.pay_status'] = $pay_status;

        $field = "a.*,f.pay_type,f.money,f.admin_name,f.alipay_username,f.alipay_account,f.add_time as wind_add_time,f.balance_withdraw,f.award_withdraw,b.driver_id,b.driver_type,driver_phone,driver_name";
        if(input('get.type') == 1){//全部数据
            $res = Db::table('xm_driver_withdraw_record a')
                ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = a.flow_id', 'LEFT')
                ->join(['xm_driver_base' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
                ->field($field)
                ->where($map)
                ->order('a.is_pay asc, a.id desc')->select();
        }else{
            $res = Db::table('xm_driver_withdraw_record a')
                ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = a.flow_id', 'LEFT')
                ->join(['xm_driver_base' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
                ->field($field)
                ->where($map)->page($page, $limit)
                ->order('a.is_pay asc, a.id desc')->select();
        }
        foreach ($res as $key => $value) {
            $res[$key]['driver_phone'] = Security::decrypt($value['driver_phone']);
            $res[$key]['wind_add_time'] = date('Y-m-d H:i:s', $value['wind_add_time']);
            $res[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            $res[$key]['money'] = sprintf("%.2f", abs($value['money']) / 100);
            $res[$key]['balance_withdraw'] = sprintf("%.2f", abs($value['balance_withdraw']) / 100);
            $res[$key]['award_withdraw'] = sprintf("%.2f", abs($value['award_withdraw']) / 100);
            if ($value['admin_time'] != '' && $value['pay_status'] == 1) {
                //字段 处理时间 为  审核时间
                $res[$key]['admin_time'] = date('Y-m-d H:i:s', $value['admin_time']);
            } elseif ($value['admin_time'] == '' && $value['pay_status'] == 1) {
                //未支付的 待支付状态 处理时间为空
                $res[$key]['admin_time'] = '';
            } else {
                //字段 处理时间 为  支付时间
                $res[$key]['admin_time'] = date('Y-m-d H:i:s', $value['pay_time']);
            }

            switch ($res[$key]['pay_status']) {
                case 1:
                    $res[$key]['pay_status'] = '待支付';
                    break;
                case 2:
                    $res[$key]['pay_status'] = '已支付';
                    break;
                case 3:
                    $res[$key]['pay_status'] = '支付失败';
                    break;
                case 4:
                    $res[$key]['pay_status'] = '支付异常';
                    break;
                default:;
            }

            switch ($res[$key]['driver_type']) {
                case 1:
                    $res[$key]['driver_type'] = '快车司机';
                    break;
                case 2:
                    $res[$key]['driver_type'] = '城际司机';
                    break;
                default:;
            }

        }

        $data = [];
        foreach ($res as $key => $value) {

            foreach ($header as $k => $v) {
                if (strpos($k, '_price') != false) {
                    $data[$key][$v] = sprintf("%.2f",$value[$k] / 100);
                    continue;
                }
                $data[$key][$v] = $value[$k];
            }
        }

        Tools::excelExport('司机端司机提现记录', $header, $data);
    }

    //审核异常
    public function withdrawSingleCheck()
    {
        $id = input('get.id');

        $field = "a.*";
        $res = Db::table('xm_driver_wallet a')
            ->join(['xm_driver_money' => 'f'], 'f.driver_id = a.driver_id', 'LEFT')
            ->join(['xm_driver' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
            ->field($field)
            ->where('a.id', $id)->find();

        $res['driver_phone'] = Security::decrypt($res['driver_phone']);
        $res['pay_time'] = $res['pay_time'] ? date('Y-m-d H:i:s', $res['pay_time']) : '';
        $res['money'] = sprintf("%.2f", abs($res['money']) / 100) . '元';
        $res['pay_status'] = '<span style="color: red;">' . pay_status()[$res['pay_status']] . '</span>';

        $fields = [];
        if ($res['pay_type'] == 1) {
            $res['pay_type'] = '支付宝';
            $fields = [
                'id' => '编号ID',
                'driver_name' => '姓名',
                'driver_phone' => '手机号',
                'pay_type' => '提现类型',
                'alipay_account' => '支付宝账号',
                'money' => '提现金额',
                'pay_status' => '支付状态',
                'remark' => '异常原因',
                'admin_name' => '审核人员',
                'pay_time' => '支付时间',
            ];
        } elseif ($res['pay_type'] == 2) {
            $res['pay_type'] = '微信';
        } else {
            $res['pay_type'] = '银行卡';
        }

        $this->assign('info', $res);
        $this->assign('fields', $fields);

        return $this->fetch();
    }

    //确认审核
    public function submits()
    {
        $id = input('post.id');
        $driver_id = input('post.driver_id')?:'';
        $audit_status = input('post.audit_status'); // 2已打款  9异常
        $error_code = input('post.error_code')?:'';
        $driver_phone = input('post.driver_phone')?:'';

        if (!$id || $driver_id == '' || !$_SESSION['admin_id'] || $error_code == '' || $driver_phone == '') {
            exit(json_encode(['code' => 0, 'msg' => '参数错误']));
        }
        $res = Db::table('xm_driver_wallet')->where('id', $id)->update(['audit_status' => $audit_status, 'admin_id' => $_SESSION['admin_id'], 'admin_name' => $_SESSION['admin_name'], 'admin_pay_time' => time(), 'content' => $error_code]);
        if ($audit_status == 2) {
            $driverWallet = Db::table('xm_driver_wallet')->where('id', $id)->find();
            $driverMoney = Db::table('xm_driver_money')->where('driver_id', $driverWallet['driver_id'])->find();
            //审核完成时 清空钱包冻结金额
            //提现金额
            //这里要判断，懒！！！
            $freeze=$driverMoney['freeze']-$driverWallet['money'];

            //$money=$driverMoney['money']+$driverWallet['money'];

            $result = Db::table('xm_driver_money')
                ->where('driver_id', $driverWallet['driver_id'])
                ->update(['freeze' => $freeze]);

            if ($result) {
                //$phone = Db::table('xm_driver_base')->where('driver_id', $driverWallet['driver_id'])->value('driver_phone');
                //**给用户推送一条信息
                exit(json_encode(['code' => 1, 'msg' => '审核完成']));
            } else {
                exit(json_encode(['code' => 0, 'msg' => '审核失败']));
            }

        } elseif ($audit_status == 9) {
            $driverWallet = Db::table('xm_driver_wallet')->where('id', $id)->find();
            $driverMoney = Db::table('xm_driver_money')->where('driver_id', $driverWallet['driver_id'])->find();
            //审核失败时 清空钱包冻结金额
            //提现金额
            //这里要判断，懒！！！
            $freeze=$driverMoney['freeze']-$driverWallet['money'];

            //这里要判断，懒！！！
            $money=$driverMoney['money']+$driverWallet['money'];

            $result = Db::table('xm_driver_money')
                ->where('driver_id', $driverWallet['driver_id'])
                ->update(['freeze' => $freeze,'money' => $money]);

            if ($result) {
                //$phone = Db::table('xm_driver_base')->where('driver_id', $driverWallet['driver_id'])->value('driver_phone');
                //**给用户推送一条信息
                exit(json_encode(['code' => 1, 'msg' => '审核完成']));
            } else {
                exit(json_encode(['code' => 0, 'msg' => '审核失败']));
            }
        }

        if($pay_status == 3) {
            //更新数组
            $update_arr = [
                'pay_status' => $pay_status,
                'admin_id' => $_SESSION['admin_id'],
                'admin_name' => $_SESSION['admin_name'],
                'admin_time' => time(),
                'error_code' => $error_code,
                'pay_time' => time(),
                'pay_admin_name'=> session('admin_name')
            ];

            //更新审核状态
            $res = Db::table('xm_driver_withdraw_record')->where('id', $id)->update($update_arr);

            if($res) {
                //失败时 清空钱包冻结金额
                $result = Db::table('xm_driver_money')->where('driver_id', $driver_id)->update(['freeze' => 0]);
                if($result) {
                    //**给用户推送一条信息
                    Tools::sendMes($driver_phone,'用户',31);
                }

            }

            //写入操作记录
            $insert_res = $this->insertLog($id);
            if(!$insert_res) {
                exit(json_encode(['code' => 2, 'msg' => '操作记录写入失败']));
            }

            if ($res) {
                exit(json_encode(['code' => 1, 'msg' => '审核完成']));
            } else {
                exit(json_encode(['code' => 2, 'msg' => '审核失败']));
            }

            //exit(json_encode(['code' => 0, 'msg' => '审核状态无变化']));
        }else{

            $map['r.id'] = $id;
            //查询待支付或者支付异常的 提现数据
            $map['r.pay_status'] = ['in', [1, 4]];
            $field = 'r.*,f.driver_id,f.alipay_account,f.alipay_username,f.money,f.balance_withdraw,f.award_withdraw,b.driver_phone,m.money as wallet_money,m.freeze,m.balance,m.award_balance';
            $info = Db::table('xm_driver_withdraw_record r')
                ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = r.flow_id', 'LEFT')
                ->join(['xm_driver_base' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
                ->join(['xm_driver_money' => 'm'], 'm.driver_id = b.driver_id', 'LEFT')
                ->field($field)
                ->where($map)->find();
            $payAmount = sprintf("%.2f", abs($info['money']) / 100); //转账金额，单位：元 （金额必须大于等于0.1元)
            $wallet = Db::table('xm_driver_money')->field('money,freeze')->where('driver_id', $driver_id)->find();

            $update_arr = [
                'pay_status' => 2,
                'admin_id' => $_SESSION['admin_id'],
                'admin_name' => $_SESSION['admin_name'],
                'admin_time' => time(),
                'error_code' => $error_code,
                'pay_time' => time(),
                'pay_admin_name'=> session('admin_name')
            ];

            //更新审核状态
            $res = Db::table('xm_driver_withdraw_record')->where('id', $id)->update($update_arr);


            if ($wallet['freeze'] > 0) {
                $new_wallet_money = $wallet['money'] - $wallet['freeze'];
//pay_status
                //钱包表  订单收入扣除收入提现金额  奖励余额扣除奖励提现金额
                $new_balance = $info['balance'] - $info['balance_withdraw'];
                $new_award_balance = $info['award_balance'] - $info['award_withdraw'];

                Db::table('xm_driver_money')->where('driver_id', $info['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money, 'balance' => $new_balance, 'award_balance' => $new_award_balance]);
                //成功时 xm_driver_wallet_record  状态
                DB::table('xm_driver_wallet_record')->where(['flow_id' => $info['flow_id'], 'out_biz_no' => $info['w_common_id']])->update(['is_pay' => 1]);

                //写入操作记录表
                $this->insertLog($id);

                //**给用户推送一条信息
                $phone = Security::decrypt($info['driver_phone']);
                Tools::sendMes($phone, '用户', 30);

                exit(json_encode([
                    'code' => 1,
                    'msg' => '提现成功金额',
                    'money' => $payAmount
                ]));
            }
        }

    }

    //支付流水 列表
    public function flowList()
    {
        $sql = "SELECT `t`.* FROM (SELECT
    `a`.*,SUM(`f`.`money`) AS 'success_pay_money',COUNT(`a`.`is_pay`) AS `success_num`
  FROM
    `xm_driver_withdraw_record` AS a
      LEFT JOIN `xm_driver_withdraw_flow` AS f ON `a`.`flow_id` = `f`.`id`
  WHERE
  (`a`.`pay_status` = 2 AND `a`.`is_pay` = 1)
  GROUP BY
    `a`.`batch_no`) t ORDER BY `t`.`pay_time` DESC";

        $res = Db::query($sql);

        foreach ($res as $key => $value) {
            if (empty($value['pay_time'])) {
                $res[$key]['pay_time'] = '';
            } else {
                $res[$key]['pay_time'] = date('Y-m-d H:i:s', $value['pay_time']);
            }
            $res[$key]['success_pay_money'] = sprintf("%.2f", abs($value['success_pay_money']) / 100) . '元';
        }

        $data = json_encode($res);

        $this->assign("data", $data);
        return $this->fetch();
    }

    //支付操作记录
    public function dealLog()
    {
        $id = input('get.id');
        if ($id) {
            $res = Db::table('xm_driver_withdraw_record')->field('flow_id')->where(['id'=>$id])->find();
            $data = Db::table('xm_driver_withdraw_log')
                ->where('flow_id ='.$res['flow_id'])->order('id DESC')->select();

            if($data) {
                foreach ($data as $key => $val){
                    if($val['batch_no'] == '') {
                        $data[$key]['type'] = '单笔支付';
                    } else {
                        if($key == count($data)-1){
                            $data[$key]['type'] = '批量支付';
                        } else {
                            $data[$key]['type'] = '单笔支付';
                        }
                    }

                    switch ($val['pay_status']){
                        case 2 :
                            $data[$key]['pay_status'] = '<span style="color: green;">支付成功</span>';
                            break;
                        case 3 :
                            $data[$key]['pay_status'] = '<span style="color: #FFB800;">支付失败</span>';
                            $data[$key]['type'] = '人工处理';
                            break;
                        case 4 :
                            $data[$key]['pay_status'] = '<span style="color: red;">支付异常</span>';
                            break;
                        default:;
                    }

                    $data[$key]['pay_time'] = date('Y-m-d H:i:s', $val['pay_time']);
                }
            }

            $data = json_encode($data);
            $this->assign("data", $data);

            return $this->fetch();
        }
        return $this->fetch();

    }

    //批量支付 信息表格
    public function withdrawTable()
    {
        $config['url'] = url('withdrawBatchInfo');
        $this->assign($config);
        return $this->fetch();
    }

    //批量支付 信息
    public function withdrawBatchInfo()
    {
        $action = input('get.action');

        if ($action && $action == 'search') {
            $start = strtotime(input('get.start'));
            $end = strtotime(input('get.end'));

            input('get.start') && $map['a.add_time'] = array('egt', $start);
            input('get.end') && $map['a.add_time'] = array('elt', $end);
            input('get.start') && input('get.end') && $map['a.add_time'] = array('between', array($start, $end));

            $data['condition'] = ['start' => $start, 'end' => $end];
        }

        $map['a.is_pay'] = 0;//未支付
        $map['a.pay_status'] = 1;//待支付

        //批量提现 禁止城际司机提现 只允许快车司机提现
        $map['b.driver_type'] = 1; //  1.快车司机  2.城际司机

        //待支付总笔数
        $wait_num_total = Db::table('xm_driver_withdraw_record a')
            ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = a.flow_id', 'LEFT')
            ->join(['xm_driver_base' => 'b'],'f.driver_id = b.driver_id', 'LEFT')
            ->where($map)->count();

        //待支付总金额
        $wait_money_total = Db::table('xm_driver_withdraw_record a')
            ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = a.flow_id', 'LEFT')
            ->join(['xm_driver_base' => 'b'],'f.driver_id = b.driver_id', 'LEFT')
            ->where($map)->sum('f.money');

        $data['condition'] = [
            'wait_num_total' => $wait_num_total, 'wait_money_total' => sprintf("%.2f", abs($wait_money_total) / 100)
        ];

        echo json_encode([
            'code' => 0,
            'msg' => '',
            'data' => $data
        ]);

    }

    //单笔支付 支付宝单笔支付接口
    public function withdrawSingle()
    {
        $id = input('post.id');
        $id && $map['r.id'] = $id;

        //查询待支付或者支付异常的 提现数据
        $map['r.pay_status'] = ['in', [1, 4]];

        $field = 'r.*,f.driver_id,f.alipay_account,f.alipay_username,f.money,f.balance_withdraw,f.award_withdraw,b.driver_phone,m.money as wallet_money,m.freeze,m.balance,m.award_balance';
        $info = Db::table('xm_driver_withdraw_record r')
            ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = r.flow_id', 'LEFT')
            ->join(['xm_driver_base' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
            ->join(['xm_driver_money' => 'm'], 'm.driver_id = b.driver_id', 'LEFT')
            ->field($field)
            ->where($map)->find();

        if (empty($info)) {
            exit(json_encode(['code' => 2, 'msg' => '没有可提现数据']));
        }

        $pay_time = time();

        $outTradeNo = $info['w_common_id'];   //商户转账唯一订单号
        $payAmount = sprintf("%.2f", abs($info['money']) / 100); //转账金额，单位：元 （金额必须大于等于0.1元)

        $account = $info['alipay_account'];
        $realName = $info['alipay_username'];

//        /*
//         * 沙箱 测试 账户
//         */
//        $account = 'ghhyxp6076@sandbox.com';
//        $realName = '沙箱环境';
//        //end

        $payer_show_name = '';
        $remark = '提现';

        //检查 钱包金额 是否>= 冻结金额  冻结金额 是否= 提现金额    冻结金额 是否>0
        if ($info['wallet_money'] < $info['freeze'] || $info['freeze'] != abs($info['money']) || $info['freeze'] <= 0) {

            $upd_data = [
                'is_pay' => 1,
                'pay_status' => 4,
                'pay_admin_name' => session('admin_name'),
                'pay_time' => $pay_time,
                'remark' => '提现金额或冻结金额数据有误'
            ];
            //异常 插入log表
            DB::table('xm_driver_withdraw_record')->where(['id'=>$info['id']])->update($upd_data);
            $this->insertLog($info['id']);
            exit(json_encode(['code' => 2, 'msg' =>$info['alipay_username'] . '_提现数据有误']));
        }


        $pay_res = $this->transfers($outTradeNo, $payAmount, $account, $realName, $payer_show_name, $remark);

        //基础字段
        $data = [
            'is_pay' => 1, // 0未支付  1已发起支付
            'pay_admin_name' => session('admin_name'),
            'pay_time' => $pay_time,
        ];

        if ($pay_res['code'] == '10000') { //成功

            $data['pay_status'] = 2; //已支付
            $data['pay_date'] = $pay_res['pay_date'];
            $data['order_id'] = $pay_res['order_id'];
            $data['pay_alipay_account'] = $pay_res['payer_show_name'];
            $data['error_code'] = $pay_res['msg'].':订单号_'.$pay_res['order_id'];
            $data['remark'] = $pay_res['msg'];
            $update_data_success = $data;
            $update_res = DB::table('xm_driver_withdraw_record')->where('id', $info['id'])
                ->update($update_data_success);

            if ($update_res) {
                //成功时  清空钱包冻结金额  并且钱包扣除 提现金额
                $wallet = Db::table('xm_driver_money')->field('money,freeze')->where('driver_id', $info['driver_id'])->find();
                if ($wallet['freeze'] > 0) {
                    $new_wallet_money = $wallet['money'] - $wallet['freeze'];

                    //钱包表  订单收入扣除收入提现金额  奖励余额扣除奖励提现金额
                    $new_balance = $info['balance'] - $info['balance_withdraw'];
                    $new_award_balance = $info['award_balance'] - $info['award_withdraw'];

                    Db::table('xm_driver_money')->where('driver_id', $info['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money, 'balance' => $new_balance, 'award_balance' => $new_award_balance]);
                    //成功时 xm_driver_wallet_record  状态
                    DB::table('xm_driver_wallet_record')->where(['flow_id' => $info['flow_id'], 'out_biz_no' => $info['w_common_id']])->update(['is_pay' => 1]);

                    //写入操作记录表
                    $this->insertLog($id);

                    //**给用户推送一条信息
                    $phone = Security::decrypt($info['driver_phone']);
                    Tools::sendMes($phone, '用户', 30);

                    exit(json_encode([
                        'code' => 1,
                        'msg' => '提现成功金额',
                        'money' => $payAmount
                    ]));
                }

                exit(json_encode([
                    'code' => 1,
                    'msg' => '钱包数据更新异常',
                    'money' => $payAmount
                ]));

            } else {
                //调查询接口
                $transfers_query_res = $this->transfers_query($outTradeNo);
                if ($transfers_query_res['code'] == '10000' && $transfers_query_res['status'] == 'SUCCESS') {

                    DB::table('xm_driver_withdraw_record')->where('id', $info['id'])
                        ->update($update_data_success);

                    //成功时  更新xm_driver_wallet_record 状态
                    DB::table('xm_driver_wallet_record')->where(['flow_id' => $info['flow_id'], 'out_biz_no' => $info['w_common_id']])->update(['is_pay' => 1]);
                    //成功时  清空钱包冻结金额  并且钱包扣除 提现金额
                    $wallet = Db::table('xm_driver_money')->field('money,freeze')->where('driver_id', $info['driver_id'])->find();
                    if ($wallet['freeze'] > 0) {
                        $new_wallet_money = $wallet['money'] - $wallet['freeze'];

                        //钱包表  订单收入扣除收入提现金额  奖励余额扣除奖励提现金额
                        $new_balance = $info['balance'] - $info['balance_withdraw'];
                        $new_award_balance = $info['award_balance'] - $info['award_withdraw'];

                        Db::table('xm_driver_money')->where('driver_id', $info['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money, 'balance' => $new_balance, 'award_balance' => $new_award_balance]);

                        //写入操作记录表
                        $this->insertLog($id);

                        //**给用户推送一条信息
                        $phone = Security::decrypt($info['driver_phone']);
                        Tools::sendMes($phone, '用户', 30);

                        exit(json_encode([
                            'code' => 1,
                            'msg' => '提现成功金额',
                            'money' => $payAmount
                        ]));
                    }

                    exit(json_encode([
                        'code' => 1,
                        'msg' => '钱包数据更新异常',
                        'money' => $payAmount
                    ]));

                } else {
                    //查询失败  走异常
                    $data['pay_status'] = 4; //支付异常
                    $data['error_code'] = '查询接口返回-'.$transfers_query_res['code'] . '_'  . $transfers_query_res['msg'] . ':' .$transfers_query_res['sub_code'].'('. $transfers_query_res['sub_msg'].')';
                    $update_data_abnormal = $data;
                    DB::table('xm_driver_withdraw_record')->where('id', $info['id'])
                        ->update($update_data_abnormal);

                    //写入操作记录表
                    $this->insertLog($id);

                    exit(json_encode([
                        'code' => 1,
                        'msg' => '提现异常金额',
                        'money' => $payAmount
                    ]));
                }
            }
        } else {
////                系统繁忙   "sub_code": "isp.unknow-error"
//                if($pay_res['sub_code'] == "isp.unknow-error") {//可能发生了网络或者系统异常，导致无法判定准确的转账结果。此时，商户不能直接当做转账成功或者失败处理，可以考虑采用相同的out_biz_no重发请求，或者通过调用“(alipay.fund.trans.order.query)”来查询该笔转账订单的最终状态。

            //单笔支付失败返回信息 插入log表
            $pay_data = '支付接口返回'.'-'.$pay_res['code'].'_'.$pay_res['msg'].'_'.$pay_res['sub_code'].'_'.$pay_res['sub_msg'];
            Db::table('xm_driver_withdraw_record')->where('id', $info['id'])->update(['remark'=>$pay_data]);

            //调用支付宝 查询接口
            $query_res = $this->transfers_query($outTradeNo);
            if ($query_res['code'] == '10000') {  //支付宝已转账成功
                $data['pay_status'] = 2; //已支付
                $data['pay_date'] = $query_res['pay_date'];
                $data['order_id'] = $query_res['order_id'];
                $data['error_code'] = $query_res['msg'].':订单号_'.$query_res['order_id'];
                $data['remark'] = $query_res['msg'];
                $query_data_success = $data;
                DB::table('xm_driver_withdraw_record')->where('id', $info['id'])
                    ->update($query_data_success);

                //成功时  更新xm_driver_wallet_record  状态
                DB::table('xm_driver_wallet_record')->where(['flow_id' => $info['flow_id'], 'out_biz_no' => $info['w_common_id']])->update(['is_pay' => 1]);
                //成功时  清空钱包冻结金额  并且钱包扣除 提现金额
                $wallet = Db::table('xm_driver_money')->field('money,freeze')->where('driver_id', $info['driver_id'])->find();
                if ($wallet['freeze'] > 0) {
                    $new_wallet_money = $wallet['money'] - $wallet['freeze'];
                    //钱包表  订单收入扣除收入提现金额  奖励余额扣除奖励提现金额
                    $new_balance = $info['balance'] - $info['balance_withdraw'];
                    $new_award_balance = $info['award_balance'] - $info['award_withdraw'];

                    Db::table('xm_driver_money')->where('driver_id', $info['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money, 'balance' => $new_balance, 'award_balance' => $new_award_balance]);

                    //写入操作记录表
                    $this->insertLog($id);

                    //**给用户推送一条信息
                    $phone = Security::decrypt($info['driver_phone']);
                    Tools::sendMes($phone, '用户', 30);

                    exit(json_encode([
                        'code' => 1,
                        'msg' => '提现成功金额',
                        'money' => $payAmount
                    ]));
                }

                exit(json_encode([
                    'code' => 1,
                    'msg' => '钱包数据更新异常',
                    'money' => $payAmount
                ]));

            } elseif ($query_res['code'] == '40004' || $query_res['sub_code'] == 'ORDER_NOT_EXIST' || $query_res['status'] == 'INIT' || $query_res['status'] == 'DEALING') {//ORDER_NOT_EXIST    转账订单不存在   转账订单不存在的原因,可能是转账还在处理中,也可能是转账处理失败,导致转账订单没有落地。商户首先需要检查该订单号是否确实是自己发起的, 如果确认是自己发起的转账订单,请不要直接当作转账失败处理,请隔几分钟再尝 试查询,或者通过相同的 out_biz_no 再次发起转账。如果误把还在转账处理中的订单直接当转账失败处理,商户自行承担因此而产生的所有损失。
                //状态转为异常
                $data['pay_status'] = 4; //支付异常
                $data['error_code'] = '查询接口返回-'.$query_res['code'] . '_'  . $query_res['msg'] . ':' .$query_res['sub_code'].'('. $query_res['sub_msg'].')';
                $query_data_abnormal = $data;
                DB::table('xm_driver_withdraw_record')->where('id', $info['id'])
                    ->update($query_data_abnormal);

                //写入操作记录表
                $this->insertLog($id);

                exit(json_encode([
                    'code' => 1,
                    'msg' => '提现异常金额',
                    'money' => $payAmount
                ]));

            } else {
                //异常
                $data['pay_status'] = 4; //支付异常
                $data['error_code'] = '查询接口返回-'.$query_res['code'] . '_'  . $query_res['msg'] . ':' .$query_res['sub_code'].'('. $query_res['sub_msg'].')';
                $query_data_fail = $data;
                DB::table('xm_driver_withdraw_record')->where('id', $info['id'])
                    ->update($query_data_fail);

                //写入操作记录表
                $this->insertLog($id);

                exit(json_encode([
                    'code' => 1,
                    'msg' => '提现异常金额：',
                    'money' => $payAmount
                ]));
            }
        }
    }

//单笔支付  循环调用 支付宝单笔支付接口
    public function withdrawBatch()
    {
        set_time_limit(1000);//脚本最长执行时间

        $start = strtotime(input('post.start'));
        $end = strtotime(input('post.end'));

        input('post.start') && $map['r.add_time'] = array('egt', $start);
        input('post.end') && $map['r.add_time'] = array('elt', $end);
        input('post.start') && input('post.end') && $map['r.add_time'] = array('between', array($start, $end));

        //查询待支付提现列表
        $map['r.is_pay'] = 0;
        $map['r.pay_status'] = 1;

        //新增 城际司机不给批量提现  只允许快车司机
        $map['b.driver_type'] = 1;

        $field = 'r.*,f.driver_id,f.alipay_account,f.alipay_username,f.money,f.balance_withdraw,f.award_withdraw,b.driver_phone,m.money as wallet_money,m.freeze,m.balance,m.award_balance';
        $list = Db::table('xm_driver_withdraw_record r')
            ->join(['xm_driver_withdraw_flow' => 'f'], 'f.id = r.flow_id', 'LEFT')
            ->join(['xm_driver_base' => 'b'], 'b.driver_id = f.driver_id', 'LEFT')
            ->join(['xm_driver_money' => 'm'], 'm.driver_id = b.driver_id', 'LEFT')
            ->field($field)
            ->where($map)->select();

        if (empty($list)) {
            exit(json_encode(['code' => 2, 'msg' => '没有可提现数据']));
        }

        //插入提现批次号
        $batch_no = date('YmdHis', time());
        $pay_time = time();

        $already_pay_money = 0.00; //成功转账钱数
        $withdraw_success_num = 0; //成功笔数
        $fail_pay_money = 0.00; //失败钱数
        $withdraw_fail_num = 0;  //失败笔数
        $abnormal_pay_money = 0.00; //异常钱数
        $withdraw_abnormal_num = 0; //异常笔数

//        $total = count($list);
//        session('total_count',$total);
//        $x = 0;
        foreach ($list as $key => $value) {

            $outTradeNo = $value['w_common_id'];   //商户转账唯一订单号
            $payAmount = sprintf("%.2f", abs($value['money']) / 100); //转账金额，单位：元 （金额必须大于等于0.1元)

            $account = $value['alipay_account'];
            $realName = $value['alipay_username'];

//            /*
//             * 沙箱 测试 账户
//             */
//            $account = 'ghhyxp6076@sandbox.com';
//            $realName = '沙箱环境';
//            //end

            $payer_show_name = '';
            $remark = '提现';

            //检查 钱包金额 是否>= 冻结金额  冻结金额 是否= 提现金额    冻结金额 是否>0
            if ($value['wallet_money'] < $value['freeze'] || $value['freeze'] != abs($value['money']) || $value['freeze'] <= 0) {
                $upd_data = [
                    'is_pay' => 1,
                    'pay_status' => 4,
                    'pay_admin_name' => session('admin_name'),
                    'batch_no' => $batch_no,
                    'pay_time' => $pay_time,
                    'remark' => '提现金额或冻结金额数据有误'
                ];
                //异常
                DB::table('xm_driver_withdraw_record')->where(['id'=>$value['id']])->update($upd_data);
                $this->insertLog($value['id']);

                $withdraw_abnormal_num++;
                $abnormal_pay_money += $payAmount;
            } else {

                $pay_res = $this->transfers($outTradeNo, $payAmount, $account, $realName, $payer_show_name, $remark);

                //基础字段
                $data = [
                    'is_pay' => 1, // 0未支付  1已发起支付
                    'pay_admin_name' => session('admin_name'),
                    'pay_time' => $pay_time,
                    'batch_no' => $batch_no,
                ];

                if ($pay_res['code'] == '10000') { //成功

                    $data['pay_status'] = 2; //已支付
                    $data['pay_date'] = $pay_res['pay_date'];
                    $data['order_id'] = $pay_res['order_id'];
                    $data['pay_alipay_account'] = $pay_res['payer_show_name'];
                    $data['error_code'] = $pay_res['msg'].':订单号_'.$pay_res['order_id'];
                    $data['remark'] = $pay_res['msg'];
                    $update_data_success = $data;
                    $update_res = DB::table('xm_driver_withdraw_record')->where('id', $value['id'])
                        ->update($update_data_success);

                    if ($update_res) {
                        //成功时  清空钱包冻结金额  并且钱包扣除 提现金额
                        $wallet = Db::table('xm_driver_money')->field('money,freeze')->where('driver_id', $value['driver_id'])->find();
                        if ($wallet['freeze'] > 0) {
                            $new_wallet_money = $wallet['money'] - $wallet['freeze'];

                            //钱包表  订单收入扣除收入提现金额  奖励余额扣除奖励提现金额
                            $new_balance = $value['balance'] - $value['balance_withdraw'];
                            $new_award_balance = $value['award_balance'] - $value['award_withdraw'];

                            Db::table('xm_driver_money')->where('driver_id', $value['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money, 'balance' => $new_balance, 'award_balance' => $new_award_balance]);
                            //成功时  更新xm_driver_wallet_record  状态
                            DB::table('xm_driver_wallet_record ')->where(['flow_id' => $value['flow_id'], 'out_biz_no' => $value['w_common_id']])->update(['is_pay' => 1]);

                            //写入操作记录表
                            $this->insertLog($value['id']);

                            //**给用户推送一条信息
                            $phone = Security::decrypt($value['driver_phone']);
                            Tools::sendMes($phone, '用户', 30);

                            //成功条数 +1
                            $withdraw_success_num++;
                            $already_pay_money += $payAmount;
                        }
                    } else {
                        //调查询接口
                        $transfers_query_res = $this->transfers_query($outTradeNo);
                        if ($transfers_query_res['code'] == '10000' && $transfers_query_res['status'] == 'SUCCESS') {

                            DB::table('xm_driver_withdraw_record')->where('id', $value['id'])
                                ->update($update_data_success);

                            //成功时  更新xm_driver_wallet_record  状态
                            DB::table('xm_driver_wallet_record')->where(['flow_id' => $value['flow_id'], 'out_biz_no' => $value['w_common_id']])->update(['is_pay' => 1]);
                            //成功时  清空钱包冻结金额  并且钱包扣除 提现金额
                            $wallet = Db::table('xm_driver_money')->field('money,freeze')->where('driver_id', $value['driver_id'])->find();
                            if ($wallet['freeze'] > 0) {
                                $new_wallet_money = $wallet['money'] - $wallet['freeze'];

                                //钱包表  订单收入扣除收入提现金额  奖励余额扣除奖励提现金额
                                $new_balance = $value['balance'] - $value['balance_withdraw'];
                                $new_award_balance = $value['award_balance'] - $value['award_withdraw'];

                                Db::table('xm_driver_money')->where('driver_id', $value['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money, 'balance' => $new_balance, 'award_balance' => $new_award_balance]);

                                //写入操作记录表
                                $this->insertLog($value['id']);

                                //**给用户推送一条信息
                                $phone = Security::decrypt($value['driver_phone']);
                                Tools::sendMes($phone, '用户', 30);

                                $withdraw_success_num++;
                                $already_pay_money += $payAmount;
                            }

                        } else {
                            //查询失败  走异常
                            $data['pay_status'] = 4; //支付异常
                            $data['error_code'] = '查询接口返回-'.$transfers_query_res['code'] . '_'  . $transfers_query_res['msg'] . ':' .$transfers_query_res['sub_code'].'('. $transfers_query_res['sub_msg'].')';
                            $update_data_abnormal = $data;
                            DB::table('xm_driver_withdraw_record')->where('id', $value['id'])
                                ->update($update_data_abnormal);

                            //写入操作记录表
                            $this->insertLog($value['id']);

                            $withdraw_abnormal_num++;
                            $abnormal_pay_money += $payAmount;
                        }
                    }
                } else {
////                系统繁忙   "sub_code": "isp.unknow-error"
//                if($pay_res['sub_code'] == "isp.unknow-error") {//可能发生了网络或者系统异常，导致无法判定准确的转账结果。此时，商户不能直接当做转账成功或者失败处理，可以考虑采用相同的out_biz_no重发请求，或者通过调用“(alipay.fund.trans.order.query)”来查询该笔转账订单的最终状态。

                    //支付失败返回信息
                    $pay_data = '支付接口返回'.'-'.$pay_res['code'].'_'.$pay_res['msg'].'_'.$pay_res['sub_code'].'_'.$pay_res['sub_msg'];
                    Db::table('xm_driver_withdraw_record')->where('id', $value['id'])->update(['remark'=>$pay_data]);

                    //调用支付宝 查询接口
                    $query_res = $this->transfers_query($outTradeNo);
                    if ($query_res['code'] == '10000') {  //支付宝已转账成功
                        $data['pay_status'] = 2; //已支付
                        $data['pay_date'] = $query_res['pay_date'];
                        $data['order_id'] = $query_res['order_id'];
                        $data['error_code'] = $query_res['msg'].':订单号_'.$query_res['order_id'];
                        $data['remark'] = $query_res['msg'];
                        $query_data_success = $data;
                        DB::table('xm_driver_withdraw_record')->where('id', $value['id'])
                            ->update($query_data_success);

                        //成功时  更新xm_driver_wallet_record  状态
                        DB::table('xm_driver_wallet_record')->where(['flow_id' => $value['flow_id'], 'out_biz_no' => $value['w_common_id']])->update(['is_pay' => 1]);
                        //成功时  清空钱包冻结金额  并且钱包扣除 提现金额
                        $wallet = Db::table('xm_driver_money')->field('money,freeze')->where('driver_id', $value['driver_id'])->find();
                        if ($wallet['freeze'] > 0) {
                            $new_wallet_money = $wallet['money'] - $wallet['freeze'];

                            //钱包表  订单收入扣除收入提现金额  奖励余额扣除奖励提现金额
                            $new_balance = $value['balance'] - $value['balance_withdraw'];
                            $new_award_balance = $value['award_balance'] - $value['award_withdraw'];

                            Db::table('xm_driver_money')->where('driver_id', $value['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money, 'balance' => $new_balance, 'award_balance' => $new_award_balance]);

//                            Db::table('xm_driver_money')->where('driver_id', $value['driver_id'])->update(['freeze' => 0, 'money' => $new_wallet_money]);

                            //写入操作记录表
                            $this->insertLog($value['id']);

                            //**给用户推送一条信息
                            $phone = Security::decrypt($value['driver_phone']);
                            Tools::sendMes($phone, '用户', 30);

                            $withdraw_success_num++;
                            $already_pay_money += $payAmount;
                        }

                    } elseif ($query_res['code'] == '40004' || $query_res['sub_code'] == 'ORDER_NOT_EXIST' || $query_res['status'] == 'INIT' || $query_res['status'] == 'DEALING') {//ORDER_NOT_EXIST    转账订单不存在   转账订单不存在的原因,可能是转账还在处理中,也可能是转账处理失败,导致转账订单没有落地。商户首先需要检查该订单号是否确实是自己发起的, 如果确认是自己发起的转账订单,请不要直接当作转账失败处理,请隔几分钟再尝 试查询,或者通过相同的 out_biz_no 再次发起转账。如果误把还在转账处理中的订单直接当转账失败处理,商户自行承担因此而产生的所有损失。
                        //状态转为异常
                        $data['pay_status'] = 4; //支付异常
                        $data['error_code'] = '查询接口返回-'.$query_res['code'] . '_'  . $query_res['msg'] . ':' .$query_res['sub_code'].'('. $query_res['sub_msg'].')';
                        $query_data_abnormal = $data;
                        DB::table('xm_driver_withdraw_record')->where('id', $value['id'])
                            ->update($query_data_abnormal);

                        //写入操作记录表
                        $this->insertLog($value['id']);

                        $withdraw_abnormal_num++;
                        $abnormal_pay_money += $payAmount;
                    } else {
                        //失败fail
                        $data['pay_status'] = 4; //支付异常
                        $data['error_code'] = '查询接口返回-'.$query_res['code'] . '_'  . $query_res['msg'] . ':' .$query_res['sub_code'].'('. $query_res['sub_msg'].')';
                        $query_data_fail = $data;
                        DB::table('xm_driver_withdraw_record')->where('id', $value['id'])
                            ->update($query_data_fail);

                        //写入操作记录表
                        $this->insertLog($value['id']);

                        $withdraw_abnormal_num++;
                        $abnormal_pay_money += $payAmount;
                    }
                }
            }

//            //进度百分比
//            $x++;
//            session('pro_count',$x);
//            $pro = sprintf("%.2f",$x/$total)*100;
//            session('pro', $pro);

        }

        echo json_encode([
            'code' => 1,
            'msg' => '',
            'data' => [
                'already_pay_money' => $already_pay_money,
                'withdraw_success_num' => $withdraw_success_num,
                'fail_pay_money' => $fail_pay_money,
                'withdraw_fail_num' => $withdraw_fail_num,
                'abnormal_pay_money' => $abnormal_pay_money,
                'withdraw_abnormal_num' => $withdraw_abnormal_num
            ]
        ]);
        exit();

    }

    //单笔转账 方法
    public function transfers($outTradeNo, $payAmount, $account, $realName, $payer_show_name, $remark)
    {
        $appid = $this->appid;  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
        //$outTradeNo = date('YmdHis') . uniqid();   //商户转账唯一订单号 5c9a0f2b0403d
        //$payAmount = 0.1;          //转账金额，单位：元 （金额必须大于等于0.1元)
        //$remark = '提现';    //转帐备注
        $signType = $this->signType;       //签名算法类型，支持RSA2和RSA，推荐使用RSA2
//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        $saPrivateKey = $this->saPrivateKey;

        $aliPay = new AlipayService($appid, $saPrivateKey, $signType);
        $result = $aliPay->doPay($payAmount, $outTradeNo, $account, $realName, $payer_show_name, $remark);

        $result = $result['alipay_fund_trans_toaccount_transfer_response'];
        if ($result['code'] && $result['code'] == '10000') {
            //成功
            return $result;
        } else {
            //失败
            return $result;
        }
    }

////单独测试使用
//    public function searchres()
//    {
//        $res = $this->transfers_query('WD201904131604269888');
//        var_dump($res);
//        exit();
//    }


    //单笔转账查询
    public function transfers_query($outTradeNo)
    {
        $appid = $this->appid;  //https://open.alipay.com 账户中心->密钥管理->开放平台密钥，填写添加了电脑网站支付的应用的APPID
        $outBizBo = $outTradeNo;        //商户转账唯一订单号（商户转账唯一订单号、支付宝转账单据号 至少填一个）
        $orderId = '';         //支付宝转账单据号（商户转账唯一订单号、支付宝转账单据号 至少填一个）
        $signType = $this->signType;    //签名算法类型，支持RSA2和RSA，推荐使用RSA2
//商户私钥，填写对应签名算法类型的私钥，如何生成密钥参考：https://docs.open.alipay.com/291/105971和https://docs.open.alipay.com/200/105310
        $saPrivateKey = $this->saPrivateKey;
        $aliPay = new AlipayService($appid, $saPrivateKey, $signType);
        //$aliPay = new AlipayService($appid,$saPrivateKey);
        $result = $aliPay->doQuery($outBizBo, $orderId);
        $result = $result['alipay_fund_trans_order_query_response'];

        if ($result['code'] && $result['code'] == '10000') {
            //echo '<h1>该笔款项转账成功</h1>';
            //成功
            return $result;
        } else {
            //失败
            return $result;
        }

    }


    //支付结果页
    public function withdrawBatchRes()
    {
        $res = input('get.') ?: '';
        $this->assign('data', $res);
        return $this->fetch();
    }


    /**  写入支付操作记录
     * @param $id
     */
    public function insertLog($id){
        $record = Db::table('xm_driver_withdraw_record')->find($id);
        if($record){
            $insert_data = [
                'flow_id' => $record['flow_id'],
                'batch_no' => $record['batch_no'],
                'add_time' => $record['pay_time'],
                'pay_status' => $record['pay_status'],
                'admin_id' => $record['admin_id'],
                'admin_name' => $record['admin_name'],
                'pay_admin_name' => $record['pay_admin_name'],
                'admin_time' => $record['admin_time'],
                'pay_time' => $record['pay_time'],
                'pay_date' => $record['pay_date'],
                'w_common_id' => $record['w_common_id'],
                'remark' => $record['remark'],
                'error_code' => $record['error_code'],
            ];

            //写入操作记录
            $res = DB::table('xm_driver_withdraw_log')->insert($insert_data);
            if($res){
                return true;
            }
        }

        return false;
    }

//    //查询进度
//    public function lookPro()
//    {
////        set_time_limit(10);  //设置程序执行时间
////        ignore_user_abort(true);    //设置断开连接继续执行
////        header('X-Accel-Buffering: no');    //关闭buffer
////
////        echo ob_get_clean();    //获取当前缓冲区内容并清除当前的输出缓冲
////        flush();   //刷新缓冲区的内容，输出
//
//        $total_count = session('total_count');
//        $pro_count = session('pro_count');
//
//        $pro = sprintf("%.2f",$pro_count/$total_count)*100;
//
//        if($total_count != '' && $pro_count != '') {
//            exit(json_encode(['code'=> 1,'pro'=>$pro]));
//        } else {
//            exit(json_encode(['code'=>2, 'pro'=>'']));
//        }
//
//
//    }


}